# -*- coding: utf-8 -*-
import urllib
import urllib2

import redis
import requests
from django.shortcuts import render_to_response, render, redirect
from django.template.context import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
import json
import time
import random
from .models import UserInfo, User
import hashlib
import os
from django.views.decorators.csrf import csrf_exempt

app_id = "wxaba19526e11b2f25"
app_secret = "530df50f56855b4a5488a76b37f899b2"



def index(request):
    return render_to_response('index.html',locals(),context_instance=RequestContext(request))


def r_oauth(request):
    '''
    微信网页授权

    '''
    url = "https://open.weixin.qq.com/connect/oauth2/authorize?" \
          "appid={0}&redirect_uri={1}&response_type=code&" \
          "scope=snsapi_userinfo&state=openid_required#wechat_redirect"
    redirect_uri = "http://pypages.gongchang.com/user/"
    redirect_uri = urllib.quote(redirect_uri)
    return redirect(url.format(app_id,redirect_uri))   # format() 生成一个url 与上一个反向


def get_user_info(request):
    '''
    获取用户信息
    :param request:
    :return:
    '''
    get_info = request.GET
    code = get_info.get('code','')
    if not code:
        return HttpResponse('not find code')
    token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&" \
                "grant_type=authorization_code"
    data = requests.get(token_url.format(app_id,app_secret,code))
    data = json.loads(data.content.decode('utf-8'))
    access_token = data['access_token']
    open_id = data['openid']
    refresh_token = data['refresh_token']
    if not access_token or not open_id:
        return None
    user_url = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN"
    d = requests.get(user_url.format(access_token,open_id))
    d = d.content.decode('utf-8')
    if not d:
        return None
    d= json.load(d)
    if d.has_key('errcode') and d['errcode'] == 40001:
        # access_token 过去解决
        refresh_token_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?" \
                            "appid={0}&grant_type=refresh_token&refresh_token={1}"
        r_d = requests.get(refresh_token_url.format(app_id,refresh_token))
        r_d = json.load(r_d.content.decode('utf-8'))
        access_token = r_d['access_token']
        d = requests.get(user_url.format(access_token,open_id))
        d = d.content.decode('utf-8')

    response = HttpResponse(json.dumps(d))
    response.set_cookie("userinfo", json.dumps(d), max_age=7 * 24 * 3600)  # 保存到cookie
    return response


def create_answer(request):
    result ={'data':[{"title": "本届赛事，哪个是你心目中的王中王球队？",
                               "answer": ["乌拉圭", "俄罗斯", "法国", "巴西"]},
                    {"title":"你认为，本届赛事“美中不足”的真正含义在于？",
                               "answer":["马可波罗缺席，总感觉差点什么","需要通宵看球，饿肚子", "这是其他国家踢给中、美两大国的娱乐项目" , "美国、中国不踢足球" ]},
                    {"title":"论速度和反应能力，你可以做到以下哪种？",
                              "answer":["10个人抢1个红包","吃了双汇王中王，运动圈里总是能比第二名多两步","外出吃饭总能抢到买单"]},
                    {"title":"参赛期间，参赛球员最有可能品尝到的美食是以下哪种？",
                              "answer":["马可波罗俄式烤肠",">威尼斯风味圆火腿","维也纳风味香肠","俄罗斯红肠"]}
                     ]}
    return HttpResponse(json.dumps(result))



def create_action(request):
    '''
    保存信息到数据库
    :param request:
    :return:
    '''
    get_info = request.GET
    grade = get_info.get('grade','')
    assert grade,('grade 不能为空')
    addtime = int(time.time())
    userinfo = request.COOKIES.get('userinfo')
    userinfo = json.loads(userinfo)
    avatar_url = userinfo['headimgurl']
    openid = userinfo['openid']
    nickname = userinfo['nickname']
    status = False
    msg = u'提交失败'
    if not grade:
        msg = u'参数缺失'
    if grade and avatar_url and openid and nickname:
        user = User(avatar = avatar_url,openid= openid,nickname = nickname,addtime = addtime,grade=grade)
        user.save()
        status = True
        msg = u'提交成功'
    data = {'status':status,'msg':msg}
    return HttpResponse(json.dumps(data))

def get_pic_action(request):
    get_info = request.GET
    userinfo_str = request.COOKIES.get('userinfo')
    userinfo = json.loads(userinfo_str)
    avatar = userinfo['headimgurl']
    nickname = userinfo['nickname']
    grade = get_info.get('grade', '')
    assert grade, ('grade 不能为空')
    status = True
    pic_url = ""
    msg = u""
    if not grade:
        status = False
        msg = u""
    url = u"http://shuanghui.feesun.com/worldcup/pic/?grade={0}&avatar={1}&nickname={2}"
    data = {
        "secret": u"gc7232275",
        "url": url.format(avatar, nickname, grade)

    }
    try:
        ret = requests.post('http:172.17.13.113/webshot',data=json.dumps(data))
        if not ret:
            status = False
            msg = u'请求失败'
        ret_str = ret.content.decode('utf-8')
        if isinstance(ret_str,str):
            ret_dict = json.loads(ret_str)
            if type(ret_dict) =='dict':
                pic_url = json.loads(ret.content.decode('utf-8'))['data'] if ret else ""
    except Exception as e:
        status = False
        msg = u'请求失败'

    result = {
        'status':status,
        'pic_url':pic_url,
        'msg':msg

    }
    return HttpResponse(json.dumps(result))








